﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLBH.DataModel;
using System.Data;

namespace QLBH.Model.Controller
{
    public class PhieuNhapKhoController : QLBHEntityBase<PHIEUNHAPKHO>
    {
        public static QLBHEntityBase<PHIEUNHAPKHO> GetInstance()
        {
            return new PhieuNhapKhoController();
        }
        public override PHIEUNHAPKHO Add(PHIEUNHAPKHO entity)
        {
            try
            {
                return base.Add(entity);
            }
            catch (System.Exception ex)
            {            	
                throw ex;
            }
            
        }
        public override PHIEUNHAPKHO Edit(PHIEUNHAPKHO entity)
        {  
            try
            {
                PHIEUNHAPKHO obj = FindBy(e => e.PNKID == entity.PNKID).FirstOrDefault();
                this.Context.ObjectStateManager.ChangeObjectState(obj, EntityState.Modified);

                // apply status for all children
                var childs = PhieuNhapKhoCTController.GetInstance().FindBy(mhct => mhct.PNKID == entity.PNKID);

                if (childs != null)
                {
                    foreach (PHIEUNHAPKHOCT ct in childs)
                    {
                        //PHIEUMUAHANGCT o = QLPhieuMuaHangChiTietController.Instance.FindBy(e => e.MUAHANGID == ct.MUAHANGID).FirstOrDefault();

                        if (entity.PHIEUNHAPKHOCTs.Where(c => c.MHID == ct.MHID).FirstOrDefault() == null)
                        {
                            this.Context.ObjectStateManager.ChangeObjectState(ct, EntityState.Deleted);
                        }
                        else
                        {
                            this.Context.ObjectStateManager.ChangeObjectState(ct, EntityState.Modified);
                        }
                    }
                }
                //save change
                Save();
                return entity;
            }
            catch (System.Exception ex)
            {
            	
                throw ex;
            }
            
        }
    }
}
